package xyf.p07.binsearch;

/**
 * ClassName: P0034_SearchRange
 * Description:
 * Author: xyf
 * Date: 9/7/22 7:04 PM
 * Version: 1.0
 **/
public class P0034_SearchRange
{
    //第一个满足条件的，和最后一个满足条件的
    public int[] searchRange(int[] nums, int target)
    {
        int start = 0;
        int end = nums.length - 1;

        int first = -1;
        while (start <= end)
        {
            int middle = (end - start) / 2 + start;

            if (nums[middle] == target)
            {
                if (middle == 0 || nums[middle - 1] < target)
                {
                    first = middle;
                    break;
                }
                else
                {
                    end = middle - 1;
                }
            }
            else if (nums[middle] < target)
            {
                start = middle + 1;
            }
            else
            {
                end = middle - 1;
            }
        }

        start = 0;
        end = nums.length - 1;
        int last = -1;
        while (start <= end)
        {
            int middle = (end - start) / 2 + start;

            if (nums[middle] == target)
            {
                if (middle == nums.length - 1 || nums[middle + 1] > target)
                {
                    last = middle;
                    break;
                }
                else
                {
                    start = middle + 1;
                }
            }
            else if (nums[middle] < target)
            {
                start = middle + 1;
            }
            else
            {
                end = middle - 1;
            }
        }

        return new int[]{first, last};
    }
}